package de.tg.handball;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import de.tg.handball.data.DataManager;
import de.tg.handball.data.Liga;
import de.tg.handball.data.Manschaft;
import de.tg.handball.data.TabellenEintrag;
import de.tg.handball.util.Util;

public class TabelleActivity extends Activity {

	private ListView list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		String manschaft = getIntent().getExtras().getString(
				Util.SHARE_MANSCHAFT_NAME);

		if (manschaft == null) {
			this.finish();
			return;
		}
		DataManager mgr = DataManager.getInstance();
		Liga rund = mgr.verein.getRundeByManschaft(manschaft);
		Manschaft man = mgr.verein.getManschaftByName(manschaft);

		setContentView(R.layout.tabelle);
		setTitleColor(getResources().getColor(R.color.tg_title_color));
		String title = getTitle().toString();
		title += " - " + rund.getShortName();
		setTitle(title);

		list = (ListView) findViewById(R.id.manschaft_tabelle);

		List<TabellenEintrag> tabelle = rund.getTabelle();

		if (tabelle.size() <= 1) {
			findViewById(R.id.tabelle_no).setVisibility(View.VISIBLE);
			findViewById(R.id.manschaft_tabelle).setVisibility(View.GONE);
		} else
			list.setAdapter(new TabelleAdapter(this, tabelle, man.getLigaName()));

	}

	private class TabelleAdapter extends ArrayAdapter<TabellenEintrag> {

		Activity context = null;
		String nameManschaft = null;

		public TabelleAdapter(Activity context, List<TabellenEintrag> objects,
				String nameMan) {
			super(context, R.layout.tabelle_entry, objects);
			this.context = context;
			this.nameManschaft = nameMan;
		}

		public View getView(int pos, View convertView, ViewGroup parent) {
			TabellenEintrag te = super.getItem(pos);

			if (convertView == null) {
				convertView = context.getLayoutInflater().inflate(
						R.layout.tabelle_entry, null);

			}

			TextView tx = (TextView) convertView
					.findViewById(R.id.tabelle_item_position);
			tx.setText((pos + 1) + ".");
			tx = (TextView) convertView
					.findViewById(R.id.tabelle_item_manschaft);
			tx.setText(te.getManschaft());

			if (nameManschaft.equals(te.getManschaft()))
				tx.setTextColor(getResources().getColor(R.color.tg_rot));
			else
				tx.setTextColor(getResources().getColor(R.color.tg_blau));

			tx = (TextView) convertView.findViewById(R.id.tabelle_item_punkte);
			tx.setText(te.getPunkte());
			tx = (TextView) convertView.findViewById(R.id.tabelle_item_tore);
			tx.setText(te.getEingeneTore() + ":" + te.getGegenTore());

			return convertView;
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		this.finish();
	}

}
